package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.TrafficNewOldManCount;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_01_DwsTrafficNewOldManCount extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_01_DwsTrafficNewOldManCount().init(
                4003,
                1,
                "Dws_01_DwsTrafficNewOldManCount",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //封装到一个POJO中
        SingleOutputStreamOperator<TrafficNewOldManCount> beanStream = parseToPOJO(stream);
        //开窗聚合
        SingleOutputStreamOperator<TrafficNewOldManCount> resultStream = windowAndAgg(beanStream);
        //写入到clickHouse中
        writeToClickHOuse(resultStream);
    }

    private void writeToClickHOuse(SingleOutputStreamOperator<TrafficNewOldManCount> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_newold_man_count ",TrafficNewOldManCount.class));
    }

    private SingleOutputStreamOperator<TrafficNewOldManCount> windowAndAgg(SingleOutputStreamOperator<TrafficNewOldManCount> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                    WatermarkStrategy
                            .<TrafficNewOldManCount>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                            .withTimestampAssigner((bean,ts) -> bean.getTs())

                )
                .keyBy(obj -> obj.getIsNew())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficNewOldManCount>() {
                            @Override
                            public TrafficNewOldManCount reduce(TrafficNewOldManCount bean1,
                                                                TrafficNewOldManCount bean2) throws Exception {
                                bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                                bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                                bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                                bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());
                                return bean1;
                            }

                        },
                        new ProcessWindowFunction<TrafficNewOldManCount, TrafficNewOldManCount, String, TimeWindow>() {
                            @Override
                            public void process(String key,
                                                Context ctx,
                                                Iterable<TrafficNewOldManCount> iterable,
                                                Collector<TrafficNewOldManCount> out) throws Exception {
                                TrafficNewOldManCount bean = iterable.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                if (bean.getUvCt()!=0) {
                                    //平均访问页面数
                                    bean.setAvgTrafficPage(bean.getPvCt() / bean.getUvCt());
                                    //平均在线时长
                                    bean.setAvgInLineDurSum(bean.getDurSum() / bean.getUvCt());
                                }
//                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        }
                );

    }

    private SingleOutputStreamOperator<TrafficNewOldManCount> parseToPOJO(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficNewOldManCount>() {
            private ValueState<String> dateState;
            @Override
            public void open(Configuration parameters) throws Exception {
                dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState",String.class));

            }

            @Override
            public TrafficNewOldManCount map(JSONObject obj) throws Exception {
                JSONObject common = obj.getJSONObject("common");
                JSONObject page = obj.getJSONObject("page");
                String vc = common.getString("vc");
                String ar = common.getString("ar");
                String isNew = common.getString("is_new");
                Long ts = obj.getLong("ts");
                //页面浏览数
                Long pvCt = 1l;
                //访问时长
                Long durSum = page.getLong("during_time");

                //会话总数
                Long svCt = 0l;

                String lastPageId = page.getString("last_page_id");
                if (lastPageId == null || lastPageId.length() == 0) {
                    svCt = 1l;
                }

                //独立访客数
                Long uvCt = 0l;
                //状态中存储年月日，如果来的数据的日期和状态不一样，就是当天的第一条 ucCt=1 更新状态
                //否则就不是第一条
                String date = dateState.value();
                String today = AtguiguUtil.toDate(ts);
                if (!today.equals(date)){
                    //更新状态
                    dateState.update(today);
                    uvCt = 1l;

                }
                return new TrafficNewOldManCount("","",vc,ar,isNew,uvCt,pvCt,svCt,durSum,0l,0l,ts);
            }
        });
    }
}
